<template>
  <div class="max-w-4xl mx-auto px-4 py-8">
    <div class="bg-white/80 backdrop-blur rounded-xl shadow-lg p-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">每日羊毛 管理</h1>
          <p class="text-sm text-gray-600 mt-1">使用管理员密钥进行维护。支持添加、修改、删除，图片会被转为 base64 保存（TTL 1 天）。</p>
        </div>
      </div>

      <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="bg-white rounded-md p-3 border">
          <div class="text-sm text-gray-500">管理员密钥</div>
          <input v-model="adminKey" placeholder="ADMIN_KEY" class="w-full mt-2 border rounded px-2 py-1 text-sm" />
          <div class="mt-3 text-sm text-gray-500">可用 Keys</div>
          <div class="mt-2 max-h-72 overflow-auto text-sm">
                    <div v-for="k in keys" :key="k.key" class="px-2 py-2 border-b hover:bg-gray-50 flex justify-between items-center">
                      <div @click="loadKey(k.key)" class="truncate cursor-pointer">{{ k.key }}</div>
                      <div class="text-xs flex items-center space-x-2">
                        <div class="text-gray-500">{{ formatTTL(k.ttl) }}</div>
                        <button @click="loadKey(k.key)" class="text-blue-600">编辑</button>
                      </div>
            </div>
            <div v-if="!keys.length" class="text-xs text-gray-400">暂无</div>
          </div>
          <div class="mt-3">
            <button @click="refreshKeys" class="bg-blue-600 text-white px-3 py-2 rounded text-sm">刷新</button>
            <button @click="newItem" class="border rounded px-3 py-2 ml-2 text-sm">新建</button>
          </div>
        </div>

        <div class="md:col-span-2">
          <div class="space-y-3">
            <div>
              <label class="text-sm text-gray-600">Key</label>
              <input v-model="form.key" class="w-full mt-2 border rounded px-2 py-1 text-sm" placeholder="唯一键（例如: ym-2025-11-25）" />
            </div>

            <div>
              <label class="text-sm text-gray-600">标题</label>
              <input v-model="form.title" class="w-full mt-2 border rounded px-2 py-1 text-sm" />
            </div>

            <div>
              <label class="text-sm text-gray-600">正文（支持简单 HTML）</label>
              <textarea v-model="form.content" rows="8" class="w-full mt-2 border rounded p-2 text-sm"></textarea>
            </div>

            <div>
              <label class="text-sm text-gray-600">图片（上传后会转换为 Base64）</label>
              <input type="file" @change="onFile" accept="image/*" class="mt-2" />
              <div class="mt-2 flex flex-wrap gap-2">
                <div v-for="(img, idx) in form.images" :key="idx" class="relative">
                  <img :src="img" class="w-32 h-20 object-cover rounded border" />
                  <button @click="removeImage(idx)" class="absolute -top-1 -right-1 bg-red-600 text-white text-xs px-1 rounded">×</button>
                </div>
              </div>
            </div>

            <div>
              <label class="text-sm text-gray-600">过期天数（留空或 0 表示永久）</label>
              <input type="number" v-model.number="form.days" min="0" class="w-40 mt-2 border rounded px-2 py-1 text-sm" placeholder="天数，例如：7" />
            </div>

            <div class="flex items-center space-x-2">
              <button @click="save" class="bg-green-600 text-white px-4 py-2 rounded">保存</button>
              <button @click="remove" class="bg-red-600 text-white px-4 py-2 rounded" v-if="form.key">删除</button>
              <div v-if="message" class="text-sm text-green-600">{{ message }}</div>
              <div v-if="error" class="text-sm text-red-600">{{ error }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
declare const useHead: (arg: any) => void
useHead({ title: '每日羊毛 管理 - 后台' })

const adminKey = ref(localStorage.getItem('admin_key') || '')
const keys = ref<any[]>([])
const form = ref<any>({ key: '', title: '', content: '', images: [], days: null })
const message = ref('')
const error = ref('')

function saveAdminKey() {
  localStorage.setItem('admin_key', adminKey.value)
}

async function refreshKeys() {
  message.value = ''
  error.value = ''
  saveAdminKey()
  try {
    const res = await fetch('/api/admin/ym.list', { headers: { 'x-admin-key': adminKey.value } })
    const json = await res.json()
    if (res.ok) keys.value = json.keys || []
    else error.value = json?.message || '获取 keys 失败'
  } catch (e) {
    error.value = String(e)
  }
}

async function loadKey(k: string) {
  message.value = ''
  error.value = ''
  saveAdminKey()
  try {
    const res = await fetch(`/api/admin/ym.get?key=${encodeURIComponent(k)}`, { headers: { 'x-admin-key': adminKey.value } })
    const json = await res.json()
    if (res.ok) {
      form.value.key = json.key || k
      form.value.title = json.data?.title || ''
      form.value.content = json.data?.content || ''
      form.value.images = json.data?.images || []
      // try to derive days from expiryAt if present
      if (json.data?.expiryAt) {
        const expires = new Date(json.data.expiryAt).getTime()
        const diffDays = Math.max(0, Math.ceil((expires - Date.now()) / (24 * 3600 * 1000)))
        form.value.days = diffDays
      } else {
        form.value.days = null
      }
    } else {
      error.value = json?.message || '获取失败'
    }
  } catch (e) {
    error.value = String(e)
  }
}

function newItem() {
  form.value = { key: '', title: '', content: '', images: [] }
  message.value = ''
  error.value = ''
}

function onFile(e: any) {
  const f = e.target.files && e.target.files[0]
  if (!f) return
  const reader = new FileReader()
  reader.onload = () => {
    const res = reader.result as string
    // store full data URL
    form.value.images = form.value.images || []
    form.value.images.push(res)
  }
  reader.readAsDataURL(f)
}

function removeImage(idx: number) {
  form.value.images.splice(idx, 1)
}

async function save() {
  error.value = ''
  message.value = ''
  if (!form.value.key || !form.value.key.trim()) { error.value = 'Key 不能为空'; return }
  if (form.value.days != null && form.value.days < 0) { error.value = '天数必须为非负整数'; return }
  saveAdminKey()
  try {
    const body: any = { key: form.value.key, data: { title: form.value.title, content: form.value.content, images: form.value.images } }
    if (form.value.days && Number(form.value.days) > 0) body.days = Number(form.value.days)
    const res = await fetch('/api/admin/ym.save', { method: 'POST', headers: { 'content-type': 'application/json', 'x-admin-key': adminKey.value }, body: JSON.stringify(body) })
    const json = await res.json()
    if (res.ok) {
      message.value = '已保存'
      refreshKeys()
    } else {
      error.value = json?.message || '保存失败'
    }
  } catch (e) {
    error.value = String(e)
  }
}

function formatTTL(ttl: number) {
  if (ttl === undefined || ttl === null) return ''
  if (ttl === -2) return '不存在'
  if (ttl === -1) return '永久'
  if (ttl <= 0) return '已过期'
  const days = Math.floor(ttl / 86400)
  const hours = Math.floor((ttl % 86400) / 3600)
  const mins = Math.floor((ttl % 3600) / 60)
  const parts: string[] = []
  if (days) parts.push(`${days}天`)
  if (hours) parts.push(`${hours}小时`)
  if (mins) parts.push(`${mins}分钟`)
  return parts.length ? parts.join('') : '少于1分钟'
}

async function remove() {
  if (!form.value.key) return
  if (!confirm('确认删除该 key 吗？')) return
  saveAdminKey()
  try {
    const res = await fetch('/api/admin/ym.delete', { method: 'POST', headers: { 'content-type': 'application/json', 'x-admin-key': adminKey.value }, body: JSON.stringify({ key: form.value.key }) })
    const json = await res.json()
    if (res.ok) {
      message.value = '已删除'
      newItem()
      refreshKeys()
    } else {
      error.value = json?.message || '删除失败'
    }
  } catch (e) {
    error.value = String(e)
  }
}

onMounted(() => {
  if (adminKey.value) refreshKeys()
})
</script>

<style scoped>
.prose img{max-width:100%;}
</style>
